<?php

require_once($GLOBALS['BIB'] . "Objects/val.form.mex");

class Sender {

    function SearchSender() {

    }

    function GetSender($SenderID) {
        global $__sys, $SESSCD;

        if ($SenderID == 0) {

            $Cliente[0] = 1;
            $CLVARS = $GLOBALS['MYT']->db_array("DESCRIBE Clientes");
            for ($v = 1; $v <= $CLVARS[0]; $v++) {
                $CLVAR = $CLVARS[$v]['Field'];
                $GET[1][$CLVAR] = '';
            }
            $GET[1]['CliProfile'] = 1;
            $GET[1]['CliClass'] = 1;
            $GET[1]['CliOffice'] = $_SESSION[$SESSCD];
            $GET[1]['CliFechaNacimiento'] = '1970-01-01';
            $GET[1]['CliNacionalidad'] = $__sys['Country'];
            $GET[1]['ClPais'] = $__sys['Country'];
            $GET[1]['CliDataVal1'] = '';
        } else {
            $GET = $GLOBALS['MYT']->db_array("SELECT *, DATE(CliFechaAlta) AS CliFechaAlta, DATE(CliFechaNacimiento) AS CliFechaNacimiento, OriNombre, CliHasArc AS CliHasArchive
                FROM Clientes
                        LEFT OUTER JOIN clientes_ext ON CliNumero = CliExtNumero
                        LEFT OUTER JOIN origenes ON OriNumero = CliOffice
                        LEFT OUTER JOIN sellers_invoices ON sliClient = CliNumero
                WHERE CliNumero = $SenderID");
        }
        if (!isset($GET[1]['CliPessoa'])) {
            $GET[1]['CliPessoa'] = 1;
            $GET[1]['CliConhecimento'] = 0;
            $GET[1]['CliLastSend'] = '';
        }
        $GET[1]['sliSeller'] = '';
        return $GET[1];
    }

    function AlreadyClient($SenderName) {
        $GETSENDER = $GLOBALS['MYT']->db_array("SELECT CliNumero, CliNombre, CliTelefono, CliTelefono2 FROM clientes
					WHERE CliNombre LIKE '$SenderName%'");
        $prStr = '';
        if ($GETSENDER[0] > 100) {
            $prStr .= 'alert(\'Dados incorrectos, impossivel prosseguir. Verifique o nome do cliente e contacte o administrador de sistema.\');';
        } elseif (isset($GETSENDER[1])) {
            if ($GETSENDER[0] > 10) {
                $GETSENDER[0] = 10;
            }
            $prStr .= 'if(confirm(\'Existem ' . $GETSENDER[0] . ' registo(s) com dados semelhantes aos do remetente que pretende registar, verifique que nenhum dos seguintes corresponde ao novo registo.\n\n';
            for ($i = 1; $i <= $GETSENDER[0]; $i++) {
                $prStr .= $GETSENDER[$i]['CliNumero'] . '	' . $GETSENDER[$i]['CliNombre'] . '	' . $GETSENDER[$i]['CliTelefono'] . '	' . $GETSENDER[$i]['CliTelefono2'] . '\n';
            }
            $prStr .= '\')==true) {
		document.ClientProperties.action=\'_response/call.php?get=Operative/sender\';
		subform(\'ClientProperties\',\'CLMSG\');
		}';
        }
        return $prStr;
    }

    function ExpiredClientInfo($GET) {
        global $sysTime;
        if ($GET['CliNumero'] > 0) {
            $ValData1Limit = strtotime($sysTime) - strtotime("1970-" . (1 + 3) . "-01 01:00:01");
            $ValData2Limit = strtotime($sysTime) - strtotime("1970-" . (1 + 6) . "-01 01:00:01");
            if (!isset($GET['CliDataVal1']) || $GET['CliDataVal1'] == '0000-00-00 00:00:00') {
                $GET['CliDataVal1'] = $GET['CliFechaAlta'];
            }
            if (!isset($GET['CliDataVal2']) || $GET['CliDataVal2'] == '0000-00-00 00:00:00') {
                $GET['CliDataVal2'] = $GET['CliFechaAlta'];
            }
            $Vfld1 = 0;
            $Vfld2 = 0;

            if (strtotime($GET['CliDataVal1']) < $ValData1Limit) {
                $Vfld1 = 1;
            }
            if (strtotime($GET['CliDataVal2']) < $ValData2Limit) {
                $Vfld2 = 1;
            }
            if ($Vfld1 == 1 || $Vfld2 == 1) {
                return '<script charset="utf-8" type="text/javascript">
		var properties = Ext.getCmp(\'winclupdate\');
		if(!properties) {
			var properties = new Ext.Window({
			title:\'Actualizacao de dados de Cliente\',
			autoLoad: \'_response/call.php?get=Operative/view/viewsenderupdate&SenderID=' . $GET['CliNumero'] . '&VField1=' . $Vfld1 . '&VField2=' . $Vfld2 . '\',
			modal:false,
			id:\'winclupdate\',
			width:500,
			height:400,
			closable:true,
			resizable:false
			});
			properties.show();
		}
		</script>';
            }
        }
    }

    function ValidateSenderData($toChange) {

        if ($toChange['CliNombre'] != '') {
            $toChange['CliNombre'] = req_form($toChange['CliNombre']);
        } else {
            $error = "Indique o nome do Cliente.";
        }
        if ($toChange['CliDomicilio'] != '') {
            $toChange['CliDomicilio'] = req_form($toChange['CliDomicilio']);
        } else {
            $error = "Indique a residencia do Cliente.";
        }
        $toChange['CliPortal'] = req_form($toChange['CliPortal']);
        $toChange['CliPisoPuerta'] = req_form($toChange['CliPisoPuerta']);
        if (isset($toChange['CliCiudad'])) {
            $toChange['CliCiudad'] = req_form($toChange['CliCiudad']);
        } elseif ($toChange['CliLocation'] == '') {
            $error = "Indique a localidade do Cliente.";
        } else {
            $toChange['CliCiudad'] = null;
        }
        $toChange['CliCP'] = req_form($toChange['CliCP']);
        if (isset($toChange['CliProvincia'])) {
            $toChange['CliProvincia'] = req_form($toChange['CliProvincia']);
        } else {
            $toChange['CliProvincia'] = null;
        }
        $toChange['ClPais'] = req_form($toChange['ClPais']);
        if ($toChange['CliTelefono'] != '' || $toChange['CliTelefono2'] != '') {
            $toChange['CliTelefono'] = req_form($toChange['CliTelefono']);
            $toChange['CliTelefono2'] = req_form($toChange['CliTelefono2']);
        } else {
            $error = "Indique um contacto do Cliente";
        }
        $toChange['ClObs'] = req_form($toChange['ClObs']);
        $toChange['CliRes1'] = req_form($toChange['CliRes1']);
        $toChange['CliRes2'] = req_form($toChange['CliRes2']);
        $toChange['CliMailing'] = req_form($toChange['CliMailing']);
        $toChange['CliOffice'] = req_form($toChange['CliOffice']);
        $toChange['CLCttEmail'] = req_form(strtolower($toChange['CLCttEmail']));
        $toChange['CliFechaNacimiento'] = preg_replace('^/[0-9]/-^', '', str_replace('/', '-', $toChange['CliFechaNacimiento']));
        if ($toChange['CliFechaNacimiento'] == '') {
            $toChange['CliFechaNacimiento'] = '0000-00-00';
        } else {
            $tmpBirthDate = preg_split('/-/', $toChange['CliFechaNacimiento']);
            if (count($tmpBirthDate) < 3 || checkdate($tmpBirthDate[1], $tmpBirthDate[2], $tmpBirthDate[0]) == false && checkdate($tmpBirthDate[1], $tmpBirthDate[0], $tmpBirthDate[2]) == false) {
                $toChange['CliFechaNacimiento'] = '0000-00-00';
            } else {
                if (checkdate($tmpBirthDate[1], $tmpBirthDate[2], $tmpBirthDate[0]) == false && checkdate($tmpBirthDate[1], $tmpBirthDate[0], $tmpBirthDate[2]) == true) {
                    $toChange['CliFechaNacimiento'] = $tmpBirthDate[2] . '-' . $tmpBirthDate[1] . '-' . $tmpBirthDate[0];
                }
            }
        }
        if ($toChange['CliNacionalidad'] < 0) {
            $error = "Indique a Naturalidade do Cliente.";
        }
        $toChange['CliActividad'] = req_form($toChange['CliActividad']);
        $toChange['CliMap'] = req_form($toChange['CliGender']) . substr(req_form($toChange['CliMap']), 1, 9);
        $toChange['CliLocation'] = req_form($toChange['CliLocation']);

        if (isset($error)) {
            return $error;
        } else {
            return $toChange;
        }
    }

    function NewSender() {
        $GLOBALS['MYT']->db_query("INSERT
			INTO Clientes
			(CliNombre,
				CliDomicilio,
				CliPortal,
				CliPisoPuerta,
				CliCiudad,
				CliCP,
				CliProvincia,
				ClPais,
				CliTelefono,
				CliTelefono2,
				ClObs,
				CliRes1,
				CliRes2,
				CliMailing,
				CliFechaAlta,
				CliUsuario,
				CliFechaNacimiento,
				CliNacionalidad,
				CliActividad,
				CliMap,
				CLCttEmail,
				CliOffice,
				CliLocation)
			VALUES
			('{$toChange['CliNombre']}','{$toChange['CliDomicilio']}','{$toChange['CliPortal']}',
			'{$toChange['CliPisoPuerta']}','{$toChange['CliCiudad']}','{$toChange['CliCP']}','{$toChange['CliProvincia']}','{$toChange['ClPais']}','{$toChange['CliTelefono']}',
			'{$toChange['CliTelefono2']}','{$toChange['ClObs']}','{$toChange['CliRes1']}','{$toChange['CliRes2']}','{$toChange['CliMailing']}','{$sysTime}',
			{$_SESSION[$SESSID]},'{$toChange['CliFechaNacimiento']}',{$toChange['CliNacionalidad']},'{$toChange['CliActividad']}','{$toChange['CliMap']}','{$toChange['CLCttEmail']}','{$toChange['CliOffice']}','{$toChange['CliLocation']}')");

        $Rst = $GLOBALS['MYT']->db_array("SELECT CliNumero FROM Clientes ORDER BY CliNumero DESC LIMIT 0,1");
        return $Rst[1]['CliNumero'];
    }

    function EditSender($SenderID, $toChange) {
        global $sysTime, $SESSID, $SESSCD, $SESSIP;
        $chnk = '';
        if ($toChange['CliCiudad'] > 0) {
            $chnk = " CliCiudad = '{$toChange['CliCiudad']}',
				CliProvincia = '{$toChange['CliProvincia']}',
				ClPais = {$toChange['ClPais']}, ";
        }
        if ($GLOBALS['MYT']->db_query("UPDATE
			Clientes
			SET
				CliNombre = \"{$toChange['CliNombre']}\",
				CliDomicilio = \"{$toChange['CliDomicilio']}\",
				CliPortal = \"{$toChange['CliPortal']}\",
				CliPisoPuerta = \"{$toChange['CliPisoPuerta']}\",
				CliCP = \"{$toChange['CliCP']}\",
				{$chnk}
				CliTelefono = \"{$toChange['CliTelefono']}\",
				CliTelefono2 = \"{$toChange['CliTelefono2']}\",
				ClObs = \"{$toChange['ClObs']}\",
				CliRes1 = \"{$toChange['CliRes1']}\",
				CliRes2 = \"{$toChange['CliRes2']}\",
				CliMailing = \"{$toChange['CliMailing']}\",
				CliUsuario = {$_SESSION[$SESSID]},
				CliFechaNacimiento = \"{$toChange['CliFechaNacimiento']}\",
				CliNacionalidad = {$toChange['CliNacionalidad']},
				CliActividad = \"{$toChange['CliActividad']}\",
				CliMap = \"{$toChange['CliMap']}\",
				CliLocation = \"{$toChange['CliLocation']}\",
				CliClass = \"{$toChange['CliClass']}\",
				CLCttEmail = \"{$toChange['CLCttEmail']}\",
				CliOffice = \"{$toChange['CliOffice']}\"
			WHERE CliNumero = $SenderID") == true) {


            hs_client($SenderID, $sysTime);
            return $SenderID;
        } else {
            return 0;
        }
    }

    function AgencyTransferClient($ClientID) {
        global $SESSCD;
        $GET = $GLOBALS['MYT']->db_array("SELECT OriNumero FROM origenes
		INNER JOIN clientes ON CliOffice = OriNumero
		WHERE CliNumero = '$ClientID' AND OriActivo = 1");
        if (!isset($GET[1])) {
            $GLOBALS['MYT']->db_query("UPDATE clientes SET CliOffice = $_SESSION[$SESSCD]
		WHERE CliNumero = $ClientID");
            return 'Autorizado';
        } else {
            return 'Recusado';
        }
    }

    function BlockSender($toChange) {
        global $sysTime, $SESSID, $SESSCD, $SESSIP;
        if ($toChange['blk_STATUS'] == 1) {
            if ($GLOBALS['MYT']->db_query("INSERT INTO hd_bloqueos
	(blk_Fecha, blk_Codigo, lbk_Tipo, lbk_Nivel, blk_Usuario, blk_Informacion, blk_STATUS)
	VALUES
	('$sysTime',{$toChange['blk_Codigo']},{$toChange['blk_TYPE']},{$toChange['blk_Nivel']},$_SESSION[$SESSID],'{$toChange['blk_Information']}',{$toChange['blk_STATUS']})") == true) {
                $GLOBALS['MYT']->db_query("UPDATE
			clientes
			SET CliBloqueado = 1
			WHERE CliNumero = {$toChange['blk_Codigo']}");
            }
        } else {
            if ($GLOBALS['MYT']->db_query("UPDATE hd_bloqueos
		SET
		blk_STATUS = 0,
		blk_CloseTime = '$sysTime',
		blk_CloseUser = $_SESSION[$SESSID],
		blk_CloseInformation = '{$toChange['blk_CloseInformation']}'
		WHERE blk_ID = {$toChange['blk_ID']}") == true) {
                $GLOBALS['MYT']->db_query("UPDATE
			clientes
			SET
				CliBloqueado = 0
			WHERE CliNumero = {$toChange['blk_Codigo']}");
            }
        }
    }

    function MergeSender($toChange) {
        global $sysTime, $SESSID, $SESSCD, $SESSIP;
        $CL_NEWID = $toChange['sel_CL'];
        $CL_OLDID = substr($toChange['mgr_CL'], 1, strlen($toChange['mgr_CL']));

        if ($CL_NEWID == '' || $CL_OLDID == '') {
            die('Error. contacte o admin.');
        }
        system_hs($sysTime, 'MIGR_CLIENT', $CL_NEWID);
        $Pr_ID = $GLOBALS['MYT']->db_array("SELECT logI_ID FROM hd_historicoalteracionesbasico
				WHERE logI_Proceso = 'MIGR_CLIENT'
					AND logI_User = $_SESSION[$SESSID]
					AND logI_Fecha = '$sysTime'");
        CONN('MYI');
        if (tuga_multiquery("CALL client_move ({$Pr_ID[1]['logI_ID']},{$CL_NEWID},'{$CL_OLDID}');")) {
            return true;
        } else {
            return false;
        }
    }

}

?>
